package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.dto.SeeRecordGoodsCountRequest;
import com.jmp.base.dto.SunCodeGoodsRequest;
import com.jmp.base.dto.SunCodeGoodsResponse;
import com.jmp.feign.SeeRecordFeign;
import com.jmp.feign.SunCodeFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.*;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.GoodsApiMapper;
import one.stand.mapper.SeeRecordPublicMapper;
import one.stand.model.GoodSpec;
import one.stand.model.Goods;
import one.stand.model.GoodsType;
import one.stand.model.ResultModel;
import one.stand.service.GoodsBaseService;
import one.stand.service.GoodsPhotoService;
import one.stand.service.GoodsTypeService;
import one.stand.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "商品")
@RestController
@RequestMapping("goods")
public class GoodsController {

    public final static String GOODS_IMAGE_SIZE = "?x-oss-process=image/resize,m_fill,w_540";

    @Autowired
    private GoodsApiMapper goodsApiMapper;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private SeeRecordPublicMapper seeRecordPublicMapper;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private SeeRecordFeign seeRecordFeign;
    @Autowired
    private SunCodeFeign sunCodeFeign;

    @ApiOperation("搜索")
    @GetMapping("search")
    @SecurityAuthCheck(company = true)
    public Result<GoodsSearchResponse> search(GoodsSearchRequest request) {
        final Integer companyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();
        final String keyword = SqlUtil.like(request.getKeyword());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Goods> goodsModels = goodsApiMapper.selectSearch(companyId, keyword, request.getCategoryId());

        List<GoodsSearchResponse.Goods> goodss = Lists.newArrayList();
        if (OneListUtil.isNotEmpty(goodsModels)) {
            for (Goods model : goodsModels) {
                boolean isPay = model.getShowPrice() == 1;//1 显示价格
                GoodsType goodsType = goodsTypeService.get(model.getGoodstypeId());
                String categoryName = goodsType.getGroupName().split(GoodsTypeService.SPLIT)[0];
                GoodsSearchResponse.Goods goods = GoodsSearchResponse.Goods.builder()
                        .id(model.getGoodsId())
                        .name(model.getGoodsName())
                        .price(PriceUtil.getPriceView2(isPay, model.getPrice()))
                        .path(goodsPhotoService.getPath(model.getGoodsId()) + GOODS_IMAGE_SIZE)
                        .visitNum(seeRecordPublicMapper.selectCount(SeeRecordEnums.PRODUCT.getCode(), model.getGoodsId()))
                        .categoryName(categoryName)
                        .categoryName2(goodsType.getName())
                        .hasVr(StringUtils.isNoneBlank(model.getQjVrUrl()))
                        .hasVideo(StringUtils.isNoneBlank(model.getVideoUrl()))
                        .hasAr(goodsBaseService.hasAr(model.getGoodsId()))
                        .build();
                goodss.add(goods);
            }
        }

        GoodsSearchResponse response = GoodsSearchResponse.builder()
                .build();
        response.setResult(goodss);
        response.setPage(goodsModels);
        return ResultUtil.success(response);
    }

    @ApiOperation("商品详情")
    @GetMapping("detail")
    @SecurityAuthCheck(company = true)
    public Result<GoodsDetailResponse> detail(GoodsDetailRequest request) {
        final Integer companyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();
        Goods goodsModel = goodsBaseService.getOn(request.getId());
        Assert.notNull(goodsModel, "商品不存在或已下架");
        Assert.isTrue(companyId.equals(goodsModel.getCompanyId()), "无权查看此商品");
        List<String> pics = goodsPhotoService.getListPath(request.getId());
//        BigDecimal price = goodsBaseService.getPrice(request.getId());
        final boolean isPay = goodsModel.getShowPrice() == 1;//1 显示价格
        String priceDetail = null;

        List<GoodSpec> specModels = goodsBaseService.getSpecs(request.getId());

        //规格
        List<GoodsDetailResponse.Type> types = Lists.newArrayList();
        List<GoodsDetailResponse.Model> models = Lists.newArrayList();//模型
        if (OneListUtil.isNotEmpty(specModels)) {
            GoodsDetailResponse.Type type = null;
            GoodsDetailResponse.Sku sku;
            GoodsDetailResponse.Model model;
            String price;
            for (GoodSpec specModel : specModels) {
                if (Objects.nonNull(specModel.getParentId()) && specModel.getParentId() == 0) {
                    if (Objects.nonNull(type)) {
                        types.add(type);
                    }
                    type = GoodsDetailResponse.Type.builder()
                            .name(specModel.getSpecName())
                            .content(Lists.newArrayList())
                            .build();
                } else if (Objects.nonNull(type)) {
                    String modelId = String.valueOf(specModel.getSpecId());

                    BigDecimal specPrice = Objects.nonNull(specModel.getPriceRemark()) ? specModel.getPriceRemark() : MoneyUtil.getMoney(specModel.getPrice());
                    price = PriceUtil.getPriceView(isPay, specPrice);

                    if (Objects.isNull(priceDetail)) {
                        priceDetail = price;
                    }

                    sku = GoodsDetailResponse.Sku.builder()
                            .name(specModel.getSpecAttribute())
                            .price(price)
                            .modelId(modelId)
                            .build();
                    type.getContent().add(sku);

                    if (StringUtils.isNoneBlank(specModel.getModelUrl())) {
                        model = GoodsDetailResponse.Model.builder()
                                .modelId(modelId)
                                .modelName(specModel.getSpecAttribute())
                                .modelCoverUrl(specModel.getModelPicUrl())
                                .modelDownloadUrl(specModel.getModelUrl())
                                .modelZipPath(specModel.getModelZipPath())
                                .build();
                        models.add(model);
                    }
                }
            }
            if (Objects.nonNull(type)) {
                types.add(type);
            }
        }

        final Integer cardId = RequestContextHolder.getRequestContext().getUser().getCardId();
        SunCodeGoodsRequest sunCodeGoodsRequest = SunCodeGoodsRequest.builder()
                .specId(specModels.get(0).getSpecId())
                .cardId(cardId)
                .build();
        ResultModel<SunCodeGoodsResponse> sunCodeGoodsResponseResultModel = sunCodeFeign.goods(sunCodeGoodsRequest);//分享码
        AssertUtil.isTrue(sunCodeGoodsResponseResultModel);
        String suncode = sunCodeGoodsResponseResultModel.getData().getCodeUrl();//分享码

        seeRecordFeign.goodsCount(SeeRecordGoodsCountRequest.builder().goodsId(goodsModel.getGoodsId()).build());

        GoodsDetailResponse response = GoodsDetailResponse.builder()
                .id(goodsModel.getGoodsId())
                .name(goodsModel.getGoodsName())
                .description(goodsModel.getGoodsName()) // TODO: 2019/6/22 商品描述暂无，先使用商品名称
                .types(types)
                .detail(goodsModel.getGoodsDetails())
                .vrUrl(goodsModel.getQjVrUrl())
                .pics(pics)
                .price(priceDetail)
                .modelParams(models)
                .sunCode(suncode)
                .videoUrl(goodsModel.getVideoUrl())
                .build();
        return ResultUtil.success(response);
    }

    @ApiOperation("AR产品列表")
    @GetMapping("specs")
    @SecurityAuthCheck(company = true)
    public Result<GoodsSpecsResponse> specs(GoodsSpecsRequest request) {
        final Integer companyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        if (Objects.nonNull(request.getSepcId())) {// 特定产品规格列表
            GoodSpec goodSpecModel = goodsBaseService.getSpec(request.getSepcId());
            Assert.notNull(goodSpecModel, "规格不存在");
            Integer goodsId = goodSpecModel.getGoodsId();

            PageHelper.startPage(request.getPageNum(), request.getPageSize());
            List<GoodSpec> specModels = goodsApiMapper.getSpecsByCompanyId(companyId, goodsId);

            List<GoodsSpecsResponse.Model> models = Lists.newArrayList();//模型
            if (OneListUtil.isNotEmpty(specModels)) {
                GoodsSpecsResponse.Model model;
                for (GoodSpec specModel : specModels) {
                    model = GoodsSpecsResponse.Model.builder()
                            .specId(specModel.getSpecId())
                            .modelId(String.valueOf(specModel.getSpecId()))
                            .modelName(specModel.getSpecAttribute())
                            .modelCoverUrl(specModel.getModelPicUrl() + GoodsController.GOODS_IMAGE_SIZE)
                            .modelDownloadUrl(specModel.getModelUrl())
                            .modelZipPath(specModel.getModelZipPath())
                            .build();
                    models.add(model);
                }
            }
            GoodsSpecsResponse response = new GoodsSpecsResponse();
            response.setResult(models);
            response.setPage(specModels);
            return ResultUtil.success(response);
        }

        // 模型列表
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Goods> specModels = goodsApiMapper.getGoodsByCompanyId(companyId, request.getCategoryId());

        List<GoodsSpecsResponse.Model> models = Lists.newArrayList();//模型
        if (OneListUtil.isNotEmpty(specModels)) {
            GoodsSpecsResponse.Model model;
            for (Goods goods : specModels) {
                GoodSpec specModel = goodsApiMapper.getSpec(goods.getGoodsId());
                List<String> pics = goodsPhotoService.getListPath(goods.getGoodsId());
                model = GoodsSpecsResponse.Model.builder()
                        .specId(specModel.getSpecId())
                        .modelId(String.valueOf(specModel.getSpecId()))
                        .modelName(goods.getGoodsName())
                        .modelCoverUrl(OneListUtil.isNotEmpty(pics) ? pics.get(0) + GoodsController.GOODS_IMAGE_SIZE : null)
                        .modelDownloadUrl(specModel.getModelUrl())
                        .modelZipPath(specModel.getModelZipPath())
                        .build();
                models.add(model);
            }
        }

        GoodsSpecsResponse response = new GoodsSpecsResponse();
        response.setResult(models);
        response.setPage(specModels);
        return ResultUtil.success(response);
    }

    @ApiOperation("商品详情")
    @GetMapping("details")
    public Result<GoodsDetailsResponse> details(GoodsDetailsRequest request) {
        Goods goodsModel = goodsBaseService.getOn(request.getId());
        Assert.notNull(goodsModel, "商品不存在或已下架");

        GoodsDetailsResponse response = new GoodsDetailsResponse();
        response.setDetail(goodsModel.getGoodsDetails());
        return ResultUtil.success(response);
    }
}
